# 定义一个函数,用来将openid加密保存到前端中
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData


def generate_user_save_token(openid):
    serializer = Serializer(settings.SECRET_KEY, 300)
    data = {'openid': openid}
    token = serializer.dumps(data).decode()
    return token


# 定义一个函数,用来保存在access_token中的openid取出来
def get_openid(access_token):
    #
    serializer = Serializer(settings.SECRET_KEY, 300)

    # 获取openid,可能会出现异常,放入异常捕获中
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        openid = data.get('openid')

        return openid
